import com.idealighter.game.server.context.ApplicationContext;
import com.idealighter.game.server.core.GameServer;
import com.idealighter.game.web.core.WebServer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * gameserver启动器.
 *
 */
public class Launcher {

  private static final Logger LOG = LoggerFactory.getLogger(Launcher.class);

  private static volatile boolean running = true;

  /**
   * 启动器.
   * 
   * @param args 参数 .
   */
  public static void main(String[] args) {
    try {
      ApplicationContext app = ApplicationContext.createInstance();
      final GameServer gameServer = ApplicationContext.getBean(GameServer.class);
      gameServer.start();

      final WebServer webServer = ApplicationContext.getBean(WebServer.class);
      Integer port = ApplicationContext.getProperty(Integer.class, "web.httpPort");
      webServer.init("webServer", port, app.allMembers()); // 获取所有托管类，提供给resteasy扫描
      webServer.start();

      // 注册关闭Hook，所有的关闭操作都注册到onShutDown中
      Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOG.info("服务器关闭中...");
        gameServer.shutdown();
        webServer.shutdown();
        LOG.info("服务器关闭成功");
        synchronized (Launcher.class) {
          running = false;
          Launcher.class.notify();
        }

      }));

    } catch (Exception e) {
      LOG.error("服务器启动异常", e);
      System.exit(1);
    }

    synchronized (Launcher.class) {
      while (running) {
        try {
          Launcher.class.wait();
        } catch (Throwable e) {
          LOG.error("服务器的等待异常", e);
        }
      }
    }
  }
}
